package com.kyh.service.sys.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kyh.service.sys.RoleService;
import com.kyh.sys.entity.Role;
import com.kyh.sys.mapper.RoleButtonMapper;
import com.kyh.sys.mapper.RoleMapper;
import com.kyh.sys.mapper.RoleMenuMapper;
import com.kyh.vo.BootstrapTableVoJA;
import com.kyh.vo.R;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private RoleButtonMapper roleButtonMapper;
	@Autowired
	private RoleMenuMapper roleMenuMapper;

	@Override
	@Transactional
	public R add(Role entity) throws Exception {
		
		// 添加数据
		if (roleMapper.insert(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	@Transactional
	public R edit(Role entity) throws Exception {
		
		// 更新数据
		if (roleMapper.update(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	@Transactional
	public R deleteFalse(
			Long roleId
			) throws Exception {
		
		if (roleMapper.deleteFalse(roleId) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	@Transactional
	public R deleteTrue(
			Long roleId
			) throws Exception {
		
		// 删除角色的菜单权限
		roleMenuMapper.deleteTrueByRoleId(roleId);
		
		// 删除角色的按钮权限
		roleButtonMapper.deleteTrueByRoleId(roleId);
		
		// 删除角色
		roleMapper.deleteTrue(roleId);
		
		return R.ok();
	}

	@Override
	public BootstrapTableVoJA search(Role cond) {
		
		List<Map<String, Object>> listMap = cond.queryMap();
		
		int total = cond.count();
		
        BootstrapTableVoJA vo = new BootstrapTableVoJA();
        vo.setRowsByListMap(listMap);
        vo.setTotal(total);
        
        return vo;
	}

	@Override
	public R tree() {
		
//		ConfRole con = new ConfRole();
//		con.orderBy.setOrderby("role_id");
//		con.orderBy.setSorttype("asc");

		JSONArray JARoot = new JSONArray();
//		List<Role> listRole = roleMapper.search(con);
		List<Role> listRole = new Role().setOrderby("A.role_id asc").queryList();
		for (Role role : listRole) {
			JSONObject JORoot = new JSONObject();
			JORoot.put("id", role.getRoleId());
			JORoot.put("text", role.getRoleName());
			JARoot.add(JORoot);
		}

        return R.ok(JARoot);
	}
}
